//
//  FDCalendarItem.m
//  FDCalendarDemo
//
//  Created by fergusding on 15/8/20.
//  Copyright (c) 2015年 fergusding. All rights reserved.
//

#import "FDCalendarItem.h"

NSString *const SZCalendarCellIdentifier = @"CalendarCell";

@interface FDCalendarCell : UICollectionViewCell

- (UILabel *)dayLabel;
- (UIImageView *)backImg;
- (UIImageView *)stateImg;

@property (nonatomic , strong) UIView *todayBackView;

@end

@implementation FDCalendarCell {
    
    UILabel *_dayLabel;
    UIImageView *_backImg;
    UIImageView *_stateImg;
}

- (UIImageView *)backImg {
    
    if (!_backImg) {
        
        _backImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 34, 34)];
        _backImg.centerX = ((DeviceWidth - 30) / 7)/2;
        _backImg.userInteractionEnabled = YES;
        [_backImg setImage:[UIImage imageNamed:@"calendar_select_Shared_nor"]];
        [self.contentView addSubview:_backImg];
    }
    return _backImg;
}



- (UILabel *)dayLabel {
    if (!_dayLabel) {
        
        _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 34, 34)];
        _dayLabel.textAlignment = NSTextAlignmentCenter;
        _dayLabel.font = [UIFont systemFontOfSize:16];
        _dayLabel.textColor = colorFromHex(@"#979797");
        _dayLabel.backgroundColor = [UIColor clearColor];
        _dayLabel.centerX = ((DeviceWidth - 30) / 7)/2;
        _dayLabel.userInteractionEnabled = YES;
        
        [self.contentView addSubview:_dayLabel];
        
    }
    return _dayLabel;
}

- (UIImageView *)stateImg {
    
    if (!_stateImg) {
        
        _stateImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
        CGPoint point = _dayLabel.center;
        point.y += 24.5;
        _stateImg.center = point;
        [self.contentView addSubview:_stateImg];
    }
    return _stateImg;
}


@end

#define CollectionViewHorizonMargin 15
#define CollectionViewVerticalMargin 5


typedef NS_ENUM(NSUInteger, FDCalendarMonth) {
    FDCalendarMonthPrevious = 0,
    FDCalendarMonthCurrent = 1,
    FDCalendarMonthNext = 2,
};

@interface FDCalendarItem () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
@property (strong, nonatomic) NSArray *canSelectedDate;//可选日期


@end

@implementation FDCalendarItem

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        [self setupCollectionView];
        [self setFrame:CGRectMake(0, 0, DeviceWidth, self.collectionView.frame.size.height + CollectionViewVerticalMargin * 2)];
    }
    return self;
}

- (instancetype)initWithToday:(NSDate *)today {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        self.today = today;
        [self setupCollectionView];
        [self setFrame:CGRectMake(0, 10, DeviceWidth, self.collectionView.frame.size.height + CollectionViewVerticalMargin * 2)];
    }
    return self;
}

#pragma mark - Custom Accessors

- (void)setDate:(NSDate *)date {
    
    NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM"];
    
    if (![[formatter stringFromDate:date] isEqualToString:[formatter stringFromDate:_date]] && _date) {

        _selectedIndexPath = [NSIndexPath indexPathForRow:[self weekdayOfFirstDayInDate:date] inSection:0];
    }
    
    _date = date;
    
    [self.collectionView reloadData];
}

- (void)setMarkArr:(NSArray *)markArr {
    
    self.canSelectedDate = [markArr valueForKeyPath:@"day"];
    _markArr = markArr;
}

#pragma mark - Public 

// 获取date的下个月日期
- (NSDate *)nextMonthDate {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    NSDate *nextMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.date options:NSCalendarMatchStrictly];
    return nextMonthDate;
}

// 获取date的上个月日期
- (NSDate *)previousMonthDate {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = -1;
    NSDate *previousMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.date options:NSCalendarMatchStrictly];
    return previousMonthDate;
}

#pragma mark - Private

// collectionView显示日期单元，设置其属性
- (void)setupCollectionView {
    CGFloat itemWidth = (DeviceWidth - CollectionViewHorizonMargin * 2) / 7;
    CGFloat itemHeight = 52;
    
    UICollectionViewFlowLayout *flowLayot = [[UICollectionViewFlowLayout alloc] init];
    flowLayot.sectionInset = UIEdgeInsetsZero;
    flowLayot.itemSize = CGSizeMake(itemWidth, itemHeight);
    flowLayot.minimumLineSpacing = 0;
    flowLayot.minimumInteritemSpacing = 0;
    
    CGRect collectionViewFrame = CGRectMake(CollectionViewHorizonMargin, CollectionViewVerticalMargin, DeviceWidth - CollectionViewHorizonMargin * 2, itemHeight * 6);
    self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayot];
    [self addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[FDCalendarCell class] forCellWithReuseIdentifier:@"CalendarCell"];
    
    
}

// 获取date当前月的第一天是星期几
- (NSInteger)weekdayOfFirstDayInDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.date];
    [components setDay:1];
    NSDate *firstDate = [calendar dateFromComponents:components];
    NSDateComponents *firstComponents = [calendar components:NSCalendarUnitWeekday fromDate:firstDate];
    return firstComponents.weekday - 1;
}

- (NSInteger)weekdayOfFirstDayInDate:(NSDate *)date1 {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date1];
    [components setDay:1];
    NSDate *firstDate = [calendar dateFromComponents:components];
    NSDateComponents *firstComponents = [calendar components:NSCalendarUnitWeekday fromDate:firstDate];
    return firstComponents.weekday - 1;
}

// 获取date当前月的总天数
- (NSInteger)totalDaysInMonthOfDate:(NSDate *)date {
    NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}

// 获取某月day的日期
- (NSDate *)dateOfMonth:(FDCalendarMonth)calendarMonth WithDay:(NSInteger)day {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date;
    
    switch (calendarMonth) {
        case FDCalendarMonthPrevious:
            date = [self previousMonthDate];
            break;
            
        case FDCalendarMonthCurrent:
            date = self.date;
            break;
            
        case FDCalendarMonthNext:
            date = [self nextMonthDate];
            break;
        default:
            break;
    }
    
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    [components setDay:day];
    NSDate *dateOfDay = [calendar dateFromComponents:components];
    return dateOfDay;
}


#pragma mark - UICollectionDatasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 42;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FDCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SZCalendarCellIdentifier forIndexPath:indexPath];
    
    NSInteger daysInThisMonth = [self totalDaysInMonthOfDate:self.date];
    NSInteger firstWeekday = [self weekdayOfFirstDayInDate];
    
    NSInteger day = 0;
    NSInteger i = indexPath.row;
    
    NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *todayString = [formatter stringFromDate:_today];
    
    if (i < firstWeekday) {
        
        [cell.backImg setImage:nil];
        [cell.dayLabel setText:@""];
        [cell.stateImg setImage:nil];
        
    }else if (i > firstWeekday + daysInThisMonth - 1){
        
        [cell.backImg setImage:nil];
        [cell.dayLabel setText:@""];
        [cell.stateImg setImage:nil];
        
    }else{
        day = i - firstWeekday + 1; //
        [cell.backImg setImage:[UIImage imageNamed:@"calendar_select_Shared_nor"]];
        [cell.dayLabel setText:[NSString stringWithFormat:@"%li",(long)day]];
        cell.dayLabel.textColor = colorFromHex(@"#979797");
        [cell.stateImg setImage:nil];
        
        NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.date];
        
        NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy-MM-dd"];
        
        
        NSString *dayStr = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)[comp year],(long)[comp month],(long)day];
        NSDate *dayDate = [formatter1 dateFromString:dayStr];
        NSString *dayString = [formatter1 stringFromDate:dayDate];
        
        
        if ([self.canSelectedDate containsObject:dayString]) {
            for (NSDictionary *dic in self.markArr) {
                
                if ([[dic objectForKey:@"day"] isEqualToString:dayString]) {
                    
                    if ([[dic objectForKey:@"flag"] integerValue] == 1) {
                        [cell.stateImg setImage:[UIImage imageNamed:@"calendar_status_blue_nor"]];
                    }else if([[dic objectForKey:@"flag"] integerValue] == 2) {
                        [cell.stateImg setImage:[UIImage imageNamed:@"calendar_status_orange_nor"]];
                    }
                }
            }
        }else {
            [cell.stateImg setImage:nil];
        }
        
        
        if (_selectedIndexPath == indexPath) {
            
            cell.dayLabel.textColor = colorFromHex(@"#1ebfff");
            [cell.backImg setImage:[UIImage imageNamed:@"calendar_select_blue_pres"]];
        }
        
        if ([todayString isEqualToString:dayString]) {
            
            cell.dayLabel.textColor = [UIColor whiteColor];
            [cell.backImg setImage:[UIImage imageNamed:@"calendar_today_blue_nor"]];
            
        }
         
        
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    NSInteger daysInThisMonth = [self totalDaysInMonthOfDate:self.date];
    NSInteger firstWeekday = [self weekdayOfFirstDayInDate];
    
    
    NSInteger day = 0;
    NSInteger i = indexPath.row;
    
    if (i >= firstWeekday && i <= firstWeekday + daysInThisMonth - 1) {
        day = i - firstWeekday + 1;
        
        //this month
        NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.date];
        
        NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy-MM-dd"];
        
        NSString *dayStr = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)[comp year],(long)[comp month],(long)day];
        NSDate *dayDate = [formatter1 dateFromString:dayStr];
        NSString *dayString = [formatter1 stringFromDate:dayDate];
        
        
        if ([SYAccountTool ShareAccount].account.lasttype == 1) {
            if ([self.canSelectedDate containsObject:dayString]) {
                
                _selectedIndexPath = indexPath;
                return YES;
            }
        }else {
            if ([_today compare:dayDate] == NSOrderedDescending) {
                
                _selectedIndexPath = indexPath;
                return YES;
            }
        }
        
        
        
        
    }
    
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
//    FDCalendarCell *cell = (FDCalendarCell *)[collectionView cellForItemAtIndexPath:indexPath];
//    cell.dayLabel.textColor = colorFromHex(@"#1ebfff");
//    cell.dayLabel.layer.borderColor = [colorFromHex(@"#1ebfff") CGColor];
    

    NSInteger firstWeekday = [self weekdayOfFirstDayInDate];
    
    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.date];
    
    NSInteger day = 0;
    NSInteger i = indexPath.row;
    day = i - firstWeekday + 1;
    
    NSString *selectDateStr = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)comp.year,(long)comp.month,(long)day];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-d"];
    NSDate *selectedDate = [formatter dateFromString:selectDateStr];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(calendarItem:didSelectedDate:)]) {
        [self.delegate calendarItem:self didSelectedDate:selectedDate];
    }
}

#pragma mark - date

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}

@end
